﻿using PagedList;
using SIG.Infrastructure.Configs;
using SIG.Model.LuceneSearch;
using SIG.Service.LuceneSearch;
using SIG.ViewModel.Front.LuceneSearch;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web.Mvc;

namespace SIG.WebMVC.Controllers
{
    public class SearchController : BaseController
    {
        // GET: Search
        public ActionResult Index(string searchTerm, int? page)
        {
            var vm = new SearchListVM()
            {
                SearchTerm = searchTerm,
              //  SearchField = searchField,
              //  SearchDefault = searchDefault ?? false,
                PageIndex = (page ?? 1) - 1,
                PageSize = SettingsManager.Lucene.PageSize
            };

            // create default Lucene search index directory
            if (!Directory.Exists(GoLucene._luceneDir)) Directory.CreateDirectory(GoLucene._luceneDir);

            int totalCount = 0;
            // perform Lucene search
            List<SearchData> _searchResults;          
                _searchResults =  GoLucene.Search(vm.PageIndex, vm.PageSize, out totalCount, searchTerm).ToList();

            if (string.IsNullOrEmpty(searchTerm) && !_searchResults.Any())
            {
                var pageList = GoLucene.GetAllIndexRecords().ToList();
                totalCount = pageList.Count();
                _searchResults = pageList.Skip(vm.PageIndex * vm.PageSize).Take(vm.PageSize).ToList();
            }
            
            vm.TotalCount = totalCount;
            vm.SearchIndexData = new StaticPagedList<SearchData>(_searchResults, vm.PageIndex + 1, vm.PageSize, vm.TotalCount); ;
           

            return View(vm);

        }
    }
}